package com.fast.develop.integration.web;

import com.fast.develop.core.web.MappingHandlerMapping;
import com.fast.develop.core.web.MappingInfo;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 莫寅
 * @createTime 2022-06-23 11:52
 * @desc：
 */
public class MvcMappingHandlerMapping implements MappingHandlerMapping {


    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    public MvcMappingHandlerMapping(RequestMappingHandlerMapping requestMappingHandlerMapping) {
        this.requestMappingHandlerMapping = requestMappingHandlerMapping;
    }

    @Override
    public void registerMapping(MappingInfo mapping, Object handler, Method method) {

        RequestMappingInfo requestMappingInfo = convertRequestMappingInfo(mapping);
        requestMappingHandlerMapping.registerMapping(requestMappingInfo, handler, method);
    }

    @Override
    public void unRegisterMapping(MappingInfo mapping) {
        RequestMappingInfo requestMappingInfo = convertRequestMappingInfo(mapping);
        requestMappingHandlerMapping.unregisterMapping(requestMappingInfo);
    }

    protected RequestMappingInfo convertRequestMappingInfo(MappingInfo mapping){
        RequestMethod[] requestMethods = Arrays.stream(mapping.getMethods())
                .map(requestMethod -> RequestMethod.valueOf(requestMethod.name()))
                .toArray(RequestMethod[]::new);
        RequestMappingInfo requestMappingInfo = RequestMappingInfo.paths(mapping.getPaths()).methods(requestMethods).build();
        return requestMappingInfo;
    }
}
